package com.ruoyi.common.utils;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class BatchImageBackgroundChanger {
    public static void main(String[] args) {
        // 源文件夹路径
        String sourceDirPath = "D:\\动漫采集\\线稿\\Object_3k\\1_Natural\\1_Animals\\1_Dog";
        // 输出文件夹路径
        String outputDirPath = "D:\\动漫采集\\线稿\\Object_3k\\1_Natural\\groud\\1_Animals\\1_Dog";

        File sourceDir = new File(sourceDirPath);
        File outputDir = new File(outputDirPath);

        // 检查源文件夹是否存在
        if (!sourceDir.exists() || !sourceDir.isDirectory()) {
            System.out.println("Source directory does not exist or is not a directory.");
            return;
        }

        // 创建输出文件夹（如果不存在）
        if (!outputDir.exists() && !outputDir.mkdirs()) {
            System.out.println("Failed to create output directory.");
            return;
        }

        // 获取源文件夹中的所有图片文件
        File[] files = sourceDir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (isImageFile(file)) {
                    try {
                        // 读取图片
                        BufferedImage image = ImageIO.read(file);

                        // 替换背景为白色
                        BufferedImage processedImage = replaceBackgroundWithWhite(image);

                        // 输出文件路径
                        File outputFile = new File(outputDir, file.getName());

                        // 保存处理后的图片
                        ImageIO.write(processedImage, "png", outputFile);
                        System.out.println("Processed and saved: " + outputFile.getAbsolutePath());
                    } catch (Exception e) {
                        System.err.println("Error processing file " + file.getName() + ": " + e.getMessage());
                    }
                }
            }
        }
    }

    // 检查是否为图片文件
    private static boolean isImageFile(File file) {
        String[] imageExtensions = {".jpg", ".jpeg", ".png", ".bmp", ".gif"};
        String fileName = file.getName().toLowerCase();
        for (String ext : imageExtensions) {
            if (fileName.endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    // 将图片背景替换为白色
    private static BufferedImage replaceBackgroundWithWhite(BufferedImage image) {
        // 创建新的白色背景图片
        BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2d = newImage.createGraphics();

        // 填充白色背景
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, image.getWidth(), image.getHeight());

        // 绘制原图像（保持前景）
        g2d.drawImage(image, 0, 0, null);
        g2d.dispose();

        return newImage;
    }
}

